﻿using ra2map_plus.data;
using System;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ra2map_plus.config
{
    class ApplicationConfig
    {
        private static readonly string _configDir = "config";
        private static readonly string ConfigRootPath = Path.Combine(GlobalDataHolder.AppRootPath, _configDir);

        private static readonly string HistoryProjectConfigFileName = Path.Combine(ConfigRootPath, "history.json");
        private static readonly string AppConfigFileName = Path.Combine(ConfigRootPath, "app.json");

        public List<ProjectHistory> ProjectHistories { get; }

        public AppConfig AppConfig { get; }

        public ApplicationConfig()
        {
            Directory.CreateDirectory(ConfigRootPath);

            // History暂不做
            //// 初始化项目历史记录HistoryProjectConfig
            //if (File.Exists(HistoryProjectConfigFileName))
            //{
            //    List<ProjectHistory> historyList = JsonConvert.DeserializeObject<List<ProjectHistory>>(File.ReadAllText(HistoryProjectConfigFileName));
            //    this.ProjectHistories = historyList;
            //} else
            //{
            //    this.ProjectHistories = new List<ProjectHistory>();
            //    string v = JsonConvert.SerializeObject(this.ProjectHistories);
            //    File.WriteAllText(HistoryProjectConfigFileName, v);
            //}

            // 初始化应用配置AppConfig
            if (File.Exists(AppConfigFileName))
            {
                AppConfig appConfig = JsonConvert.DeserializeObject<AppConfig>(File.ReadAllText(AppConfigFileName));
                this.AppConfig = GlobalDataHolder.DefaultAppConfig.mergeNonNullProperties(appConfig);
            }
            else
            { // 还没有配置文件，则使用默认的配置
                this.AppConfig = GlobalDataHolder.DefaultAppConfig;
            }
            string v = JsonConvert.SerializeObject(this.AppConfig, Formatting.Indented);
            File.WriteAllText(AppConfigFileName, v);
            
            GlobalDataHolder.AppConfig = this.AppConfig;
        }

        public List<ProjectHistory> AddProjectHistory(ProjectHistory projectHistory)
        {
            this.ProjectHistories.Insert(0, projectHistory);
            return this.ProjectHistories;
        }
    }
}
